package vip.aster.common.exception;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import vip.aster.common.utils.ResultCode;
import vip.aster.common.utils.ResultInfo;

import java.nio.file.AccessDeniedException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p> BusinessExceptionHandler </p>
 *
 * @author Aster
 * @since 2023/11/13 18:01
 */
@Slf4j
@RestControllerAdvice
public class BusinessExceptionHandler {

    @ExceptionHandler(value = BusinessException.class)
    public ResultInfo handleException(BusinessException e) {
        if (e.getErrorCode() != null) {
            return ResultInfo.failed(e.getErrorCode(), e.getMessage());
        }
        return ResultInfo.failed(e.getMessage());
    }

    /**
     * 处理 form data方式调用接口校验失败抛出的异常
     * @author Aster
     * @since 2023/11/16
     */
    @ExceptionHandler(value = BindException.class)
    public ResultInfo bindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getField()+fieldError.getDefaultMessage();
            }
        }
        return ResultInfo.validateFailed(message);
    }

    @ExceptionHandler(AccessDeniedException.class)
    public ResultInfo<String> handleAccessDeniedException(Exception ex) {
        return ResultInfo.failed(ResultCode.FORBIDDEN.getMessage());
    }

    /**
     * 处理 json 请求体调用接口校验失败抛出的异常
     * @author Aster
     * @since 2023/11/16
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultInfo methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> collect = fieldErrors.stream().map(o -> o.getDefaultMessage()).collect(Collectors.toList());
        return ResultInfo.validateFailed(collect.toString());
    }

    /**
     * 处理单个参数校验失败抛出的异常
     * @author Aster
     * @since 2023/11/16
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResultInfo constraintViolationExceptionHandler(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        List<String> collect = constraintViolations.stream().map(o -> o.getMessage()).collect(Collectors.toList());
        return ResultInfo.validateFailed(collect.toString());
    }

    @ExceptionHandler(Exception.class)
    public ResultInfo<String> runtimeExceptionHandler(Exception ex) {
        log.error("RuntimeException：", ex);
        return ResultInfo.failed(ex.getMessage());
    }
}
